package cn.chinasyq.photoquan.news.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.TextView;

import com.tencent.mm.sdk.openapi.WXAPIFactory;

import cn.chinasyq.photoquan.AppConstant;
import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.news.adapter.ArticleInfoAdapter;
import cn.chinasyq.photoquan.news.bean.ArticlesInfoEntity;
import cn.chinasyq.photoquan.news.bean.Favorite;
import cn.chinasyq.photoquan.news.mode.NewsMode;
import cn.chinasyq.photoquan.user.activity.LoginActivity;
import cn.chinasyq.photoquan.util.ShareSDKUtil;
import cn.chinasyq.photoquan.view.LoadView;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;
import cn.master.xlistview.view.XListView;
import cn.sharesdk.wechat.friends.Wechat;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * Created by 一搏 on 2015/11/25.
 */

public class ArticleInfoActivity extends Activity implements View.OnClickListener, ResponseHandler.OnNeedLoginListener, ResponseHandler.OnSucceedListener, ResponseHandler.OnFailedListener, TextView.OnEditorActionListener {
    public static final String UUID = "uuid";
    public static final String TAG_COMMENT = "comment";
    private static final String TAG_UP = "up";

    private String article_uuid;
    private XListView listView;
    private ArticleInfoAdapter adapter;
    private LoadView loadView;
    private Button btn_collection;
    private Button btn_share;
    private TextView tv_title;
    private ArticlesInfoEntity info;

    public void callLoginActivity() {
        Intent intent = new Intent(ArticleInfoActivity.this, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_article_info);
        article_uuid = getIntent().getStringExtra(UUID);
        listView = (XListView) findViewById(R.id.xlv_content);
        adapter = new ArticleInfoAdapter();
        listView.setAdapter(adapter);
        listView.setPullLoadEnable(true);
        listView.setPullRefreshEnable(false);
        loadView = (LoadView) findViewById(R.id.loadview);
        loadView.setStatus(LoadView.Status.loading);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText(getString(R.string.artivle_details));
        loadView.setOnReLoadClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                refreshDate();
            }
        });
        btn_collection = (Button) findViewById(R.id.btn_collection);
        btn_share = (Button) findViewById(R.id.btn_share);
        btn_collection.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        listView.setPullLoadEnable(false);
        listView.setPullRefreshEnable(false);
        listView.setXListViewListener(new XListView.IXListViewListener() {

            @Override
            public void onRefresh() {
            }

            @Override
            public void onLoadMore() {
            }
        });
        ((EditText) findViewById(R.id.et_comment)).setOnEditorActionListener(this);
        ((EditText) findViewById(R.id.et_comment)).setImeActionLabel("发送", EditorInfo.IME_ACTION_SEND);
    }

    @Override
    protected void onResume() {
        super.onResume();
        refreshDate();
    }

    private static final String TAG_LOADMORE = "loadmore";
    private static final String TAG_REFRESH = "refresh";
    private static final String TAG_FAVORITE = "favorite";

    private void initShareData(String name) {
        if (info == null || info.getShare() == null) {
            return;
        }
        ShareSDKUtil.showShare(this, name, info.getShare().getTitle(),
                info.getShare().getSummary(),
                info.getShare().getImage(),
                info.getShare().getUrl());
    }

    protected void refreshDate() {
        ResponseHandler handler = new ResponseHandler(TAG_REFRESH);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        NewsMode.obtainArticleInfo(getApplicationContext(), article_uuid, handler);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        boolean isExist = WXAPIFactory.createWXAPI(getApplicationContext(), AppConstant.APP_ID).isWXAppInstalled();
        switch (v.getId()) {
            case R.id.btn_share:
                initShareData(null);
                break;
            case R.id.btn_pyq:
                if (isExist) {
                    initShareData(WechatMoments.NAME);
                } else {
                    ToastUtil.show(getApplicationContext(), "请安装微信");
                }

                break;
            case R.id.btn_wx:
                if (isExist) {
                    initShareData(Wechat.NAME);
                } else {
                    ToastUtil.show(getApplicationContext(), "请安装微信");
                }
                break;
            case R.id.ibtn_back:
                onBackPressed();
                break;
            case R.id.btn_collection:
                ResponseHandler handler = new ResponseHandler(TAG_FAVORITE);
                handler.setOnSucceedListener(this);
                handler.setOnFailedListener(this);
                handler.setOnNeedLoginListener(this);
                NewsMode.applaudQuestion(getApplicationContext(), article_uuid, handler);
                break;
            case R.id.tv_like_num:
                temp = (CheckedTextView) v;
                upComment((String) v.getTag());
                break;
            default:
                break;
        }
    }

    @Override
    public void onNeedLogin(String tag) {
        callLoginActivity();
    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode,String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.servererrortips);
                    break;
            }
        }else {
            ToastUtil.show(getApplicationContext(),msg);
        }

        if (tag.equals(TAG_LOADMORE)) {
            listView.stopLoadMore();
        } else {
            loadView.setStatus(status == ResponseHandler.FailedStatus.DATA_ERROR ? LoadView.Status.data_error : LoadView.Status.network_error);
            listView.stopRefresh();
        }
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        if (tag.equals(TAG_REFRESH)) {
            info = (ArticlesInfoEntity) data;
            adapter.setInfoEntity((ArticlesInfoEntity) data);
            listView.setAdapter(adapter);
            listView.stopRefresh();
            if (info == null) {
                loadView.setStatus(LoadView.Status.not_data);
                return;
            } else {
                loadView.setStatus(LoadView.Status.successed);
            }

            if (info.getShare() != null) {
                btn_share.setEnabled(true);
            } else {
                btn_share.setEnabled(false);
            }

        }
        if (tag.equals(TAG_FAVORITE)) {
            Favorite favorite = (Favorite) data;
            if (favorite.isFavorite()) {
                Drawable left = getApplicationContext().getResources().getDrawable(
                        R.mipmap.icon_collectioned);
                left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
                btn_collection.setCompoundDrawables(left, null, null, null);
            }else {
                Drawable left = getApplicationContext().getResources().getDrawable(
                        R.mipmap.icon_collection);
                left.setBounds(0, 0, left.getIntrinsicWidth(), left.getIntrinsicHeight());
                btn_collection.setCompoundDrawables(left, null, null, null);
            }
        }
        if (tag.equals(TAG_COMMENT)) {
            ((EditText) findViewById(R.id.et_comment)).setText("");
            refreshDate();
        }
        if (tag.equals(TAG_UP)) {
            temp.setChecked(true);
        }

    }

    CheckedTextView temp;

    protected void sendComment(String comment) {
        ResponseHandler handler = new ResponseHandler(TAG_COMMENT);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        NewsMode.sendComment(getApplicationContext(), article_uuid, comment, handler);
    }

    protected void upComment(String uuid) {
        ResponseHandler handler = new ResponseHandler(TAG_UP);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        NewsMode.upComment(getApplicationContext(), uuid, handler);
    }

    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

        if (KeyEvent.KEYCODE_ENTER==event.getKeyCode()&&KeyEvent.ACTION_UP == event.getAction()) {
            sendComment(v.getText().toString());
        }
        return true;
    }
}
